//
//  SearchListViewController.m
//  ShouYi
//
//  Created by yrapp on 16/3/3.
//  Copyright © 2016年 yurui. All rights reserved.
//

#import "SearchListViewController.h"
#import "TaskListModel.h"

#import "searchHeaderView.h"
#import "ContentTableViewCell.h"
@interface SearchListViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate>
@property (nonatomic,strong)NSMutableArray *searchArray;
@property (nonatomic,strong)UITableView *tableView;
//搜索headerView
@property (nonatomic,strong)searchHeaderView *headerView;
@end

@implementation SearchListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    //添加tableView
    [self addTableView];
    //解析数据
    [self updataForSearch];
    //添加搜索headerView
    [self addHeaderView];
    
    //添加上拉刷新加载
    [self AddMJrefresh];
    
    // Do any additional setup after loading the view.
}
#pragma mark --- 添加视图 ---
- (void)addHeaderView {
    
    self.headerView = [[searchHeaderView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 64)];
    [self.headerView.backButton addTarget:self action:@selector(back) forControlEvents:(UIControlEventTouchUpInside)];
    self.headerView.searchButton.hidden = YES;
    [self.view addSubview:self.headerView];
    self.headerView.backgroundColor = kBackGroundColor;
    self.headerView.searchBar.delegate = self;
    
}
- (void)addTableView {
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 44, kWidth , kHeight - 64)];
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellAccessoryNone;
    [self.tableView registerClass:[ContentTableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.view addSubview:_tableView];

}


- (void)back {
    
    [self.navigationController popViewControllerAnimated:YES];
    
}

#pragma mark --- 数据处理 ---
//展示的数据
- (NSMutableArray *)searchArray {
    if (!_searchArray) {
        _searchArray = [NSMutableArray array];
    }
    return _searchArray;
}

//刷新数据 (下拉加载)
- (void)updataForSearch {
    
    //NSString *cuid = [[NSUserDefaults standardUserDefaults] objectForKey:@"CFUUID"];
    NSString *url = [KSearchList stringByAppendingString:[NSString stringWithFormat:@"&keyname=%@&pagesize=%d",self.keyname,10]];
    NSLog(@"刷新数据 %@",url);
    
    if (self.searchArray.count > 0) {
        TaskListModel *model = self.searchArray.lastObject;
        url = [url stringByAppendingString:[NSString stringWithFormat:@"&preid=%@",model.ID]];
    }
    NSLog(@"%@",url);
    
    NSURL *temUrl = [NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSLog(@"%@",[NSString stringWithFormat:@"%@",temUrl]);
    
    NSString *newUrl = [NSString stringWithFormat:@"%@",temUrl];
    
    [LORequestManger GET:newUrl success:^(id response) {
        
        NSArray *array = (NSArray *)response;
        
        for (NSDictionary *dic in array) {
            TaskListModel *model = [TaskListModel setUpDic:dic];
            [self.searchArray addObject:model];
        }
        
        [self.tableView reloadData];
        
        // 刷新结束
        [self.tableView.mj_footer endRefreshing];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        // 刷新结束
        [self.tableView.mj_footer endRefreshing];
        [self showAlertMessage:@"没有更多数据"];
        NSLog(@"%@",error);
    }];
    
}
//任务刷新 上拉
- (void)setUpDataForTaskListSHANGLAUrl:(NSString *)url{
    
    [LORequestManger GET:url success:^(id response) {
        
        //临时数据存储刷新出来的数据
        NSMutableArray *tempArray = [NSMutableArray array];
        NSArray *array = (NSArray *)response;
        //赋值刷新出来的数据
        for (NSDictionary *dic in array) {
            TaskListModel *model = [TaskListModel setUpDic:dic];
            [tempArray addObject:model];
        }
        //将原数组中的数据添加到临时数组中
        for (TaskListModel *TModel in self.searchArray) {
            [tempArray addObject:TModel];
        }
        //清空原数组,并把临时数组替换原数组
        [self.searchArray removeAllObjects];
        for (TaskListModel *tempModel in tempArray) {
            [self.searchArray addObject:tempModel];
        }
        
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"%@",error);
        [self.tableView.mj_header endRefreshing];
       
        
    }];
}



//添加上拉刷新下拉加载
//刷新 下拉加载
- (void)AddMJrefresh {
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        NSLog(@"下拉加载");
        
    [self updataForSearch];
        
    }];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        NSLog(@"上拉刷新");
        TaskListModel *model = self.searchArray.firstObject;
        NSString *url = [KSearchList stringByAppendingString:[NSString stringWithFormat:@"&keyname=%@&pagesize=%d&nextid=%@",self.keyname,10,model.ID]];
        NSURL *temUrl = [NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        NSLog(@"%@",[NSString stringWithFormat:@"%@",temUrl]);
        NSString *newUrl = [NSString stringWithFormat:@"%@",temUrl];
        [self setUpDataForTaskListSHANGLAUrl:newUrl];
    }];
}


- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    [searchBar endEditing:YES];
    [self back];
    
}


#pragma  mark UITableViewDelegate 和UITableViewDataSource
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.searchArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ContentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    
    TaskListModel *model = self.searchArray[indexPath.row];
    
    [cell setModelForTaskList:model];
    
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 120;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    self.hidesBottomBarWhenPushed = YES;
    TaskListModel *model = self.searchArray[indexPath.row];
    
    
    DetailViewController *detailVC = [[DetailViewController alloc] init];
    detailVC.webUrl = model.gourl;
    detailVC.imagesrc = model.imgsrc;
    detailVC.title = model.title;
    detailVC.type = @"detail";
    [self.navigationController pushViewController:detailVC animated:YES];
    self.hidesBottomBarWhenPushed = NO;
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark --- 提醒视图 ---
//添加 收藏提醒框图
- (void)showAlertMessage:(NSString *)message {
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"通知" message:message delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
    [alert show];
    [self performSelector:@selector(dimissAlert:) withObject:alert afterDelay:1];
    
}

// 提醒视图消失
- (void)dimissAlert:(UIAlertView *)alert {
    
    if (alert) {
        [alert dismissWithClickedButtonIndex:[alert cancelButtonIndex] animated:YES];
    }
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
